<script setup>
import PersonInfoView from './component/PersonInfo.vue'
import PolicyInfoView from './component/PolicyInfo.vue'
import WelfareInfoView from './component/WelfareInfo.vue'
import PreAuthInfoView from './component/PreAuthorization.vue'
import ClaimInfoView from './component/ClaimInfo.vue'
import OBView from './component/OB.vue'
import { ref, nextTick, onMounted, onBeforeUnmount, watch, unref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { queryCustomersList } from '@/api/home'
import { useAccountStore } from '@/stores/account'
import { Modal } from 'ant-design-vue'
import { storeToRefs } from 'pinia'
import useAppStore from '@/stores/app'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const appStore = useAppStore()

const { language } = storeToRefs(appStore)
// 脱敏
const accountStore = useAccountStore()
watch(
  () => accountStore.DESENSITIZATION,
  (newValue, oldValue) => {
    getInsuredList('sourceEye')
  }
)
const route = useRoute()
const router = useRouter()

/**
 * @param {Boolean} insuredListLoaded
 * @param {Boolean} policyInfoLoaded // 保单信息接口是否获取成功，拿到保单信息，才能获取福利信息
 * @param {Object} insuredInfo 当前默认选中的被保人信息。
 * @param {Object} policyInfo 当前选中的保单信息。
 * 是否被保人列表已经获取。
 * 获取的拿到当前的memberID,customerId,才可以获取基本信息，保单信息等接
 */

const insuredListLoaded = ref(false)
const policyInfoLoaded = ref(false)
const insuredList = ref([])
let insuredInfo = ref(null)

const selectedInsuredIdModel = ref('')
async function getInsuredList(type) {
  let res = null
  try {
    const data = {
      desensitization: accountStore.DESENSITIZATION ? '02' : '01',
      insuredId: route.query.insuredId
    }
    res = await queryCustomersList(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    insuredList.value = res.data
    if (type == 'sourceEye') return
    insuredListLoaded.value = true
    selectedInsuredIdModel.value = insuredList.value.find((item) => item.flag)?.doc_id
    insuredInfo.value = getCurrentInsuredInfo()
  }
}
let policyInfo = ref({})
let loadWerfareComp = ref(false)
let loadAuthComp = ref(false)
async function updatePolicyInfo(info) {
  loadWerfareComp.value = false
  await nextTick()
  policyInfo.value = info
  loadWerfareComp.value = true
  // 预授权初次默认值取保单年度默认值
  if (unref(loadAuthComp)) return
  loadAuthComp.value = true
}
/**
 * cc登录 首先判断是否存在权限。
 * 权限不存在，modal提示。
 */
async function hasPermission() {
  let res = null
  try {
    res = await accountStore.checAccountAuth()
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    if (res.data) {
      getInsuredList()
      return
    }
    const message = '当前用户无权限,是否跳转至综合查询页面'
    Modal.warning({
      keyboard: false,
      title: '提醒',
      okText: '确定',
      content: message,
      onOk() {
        router.push({
          path: '/',
          query: {
            ...route.query
          }
        })
      }
    })
  }
}
/**
 * cc第一次进入个人主页，进行权限校验。
 * 后续跳转到综合查询后，再跳转个人主页，无需再进行权限校验
 */
async function initData() {
  if (route.query.account && !accountStore.FetchedPermission) {
    hasPermission()
    return
  }
  getInsuredList()
}

let showScrollTopIcon = ref(false)
const handleScroll = () => {
  const element = document.getElementById('main-view')
  let scrollTop = element.scrollTop
  if (scrollTop > 10) {
    showScrollTopIcon.value = true
  } else {
    showScrollTopIcon.value = false
  }
}
onMounted(() => {
  const element = document.getElementById('main-view')
  if (element) {
    console.log('element', element)
    element.addEventListener('scroll', handleScroll)
  }
  initData()
})

onBeforeUnmount(() => {
  const element = document.getElementById('main-view')
  if (element) {
    element.removeEventListener('scroll', handleScroll(element))
  }
})
// 切换被保人
async function updateInsuredInfoFun() {
  insuredInfo.value = getCurrentInsuredInfo()
}
function getCurrentInsuredInfo() {
  const info = unref(insuredList).find((item) => item.doc_id == unref(selectedInsuredIdModel))
  return info || {}
}
function scrollToTop() {
  const element = document.getElementById('home-main')
  element.scrollIntoView({ behavior: 'smooth' })
}
function scrollIntoViewFn(id) {
  switch (id) {
    case 1:
      const policyView = document.getElementById('policy-info-view')
      policyView.scrollIntoView({ behavior: 'smooth', inline: 'nearest' })
      break
    case 2:
      const authView = document.getElementById('auth-info-view')
      authView.scrollIntoView({ behavior: 'smooth', inline: 'nearest' })
      break
    case 3:
      const claimView = document.getElementById('claim-info-view')
      claimView.scrollIntoView({ behavior: 'smooth', inline: 'nearest' })
      break
    case 4:
      const obView = document.getElementById('ob-info-view')
      obView.scrollIntoView({ behavior: 'smooth', inline: 'nearest' })
  }
}
const moduleMenuList = computed(() => {
  return [
    {
      id: 1,
      name: t('home.policy.policyInfo')
    },
    {
      id: 2,
      name: t('home.preAuth.PreAuthInfo')
    },
    {
      id: 3,
      name: t('home.claim.ClaimsInfo')
    },
    {
      id: 4,
      name: t('home.ob.OBInfo')
    }
  ]
})
</script>
<template>
  <div class="home-main" id="home-main">
    <PersonInfoView
      id="person-info-view"
      v-if="insuredListLoaded"
      :insuredList="insuredList"
      :insuredInfo="insuredInfo"
      :policyInfo="policyInfo"
      v-model="selectedInsuredIdModel"
      @updateInsuredInfoFun="updateInsuredInfoFun"
    ></PersonInfoView>
    <PolicyInfoView
      id="policy-info-view"
      v-if="insuredListLoaded"
      :insuredInfo="insuredInfo"
      @updatePolicyInfo="updatePolicyInfo"
    ></PolicyInfoView>
    <WelfareInfoView v-if="loadWerfareComp" :policyInfo="policyInfo"></WelfareInfoView>
    <PreAuthInfoView
      id="auth-info-view"
      :policyInfo="policyInfo"
      :insuredInfo="insuredInfo"
      v-if="loadAuthComp"
    ></PreAuthInfoView>
    <ClaimInfoView
      id="claim-info-view"
      v-if="insuredListLoaded"
      :insuredInfo="insuredInfo"
    ></ClaimInfoView>
    <OBView
      id="ob-info-view"
      v-if="insuredListLoaded"
      :insuredInfo="insuredInfo"
      :policyInfo="policyInfo"
    ></OBView>
    <div class="anchor-point">
      <div class="scroll-top anchor-point-style" v-if="showScrollTopIcon" @click="scrollToTop">
        <svg-icon size="26" name="anchor-scroll-top" />
      </div>
      <a-popover placement="left" overlayClassName="anchor-point-popover">
        <template #content>
          <div class="anchor-point-popover-list">
            <div
              class="anchor-point-popover-item"
              :class="{ 'anchor-point-enPopover-item': language !== 'zh' }"
              @click="scrollIntoViewFn(menu.id)"
              v-for="menu in moduleMenuList"
              :key="menu.id"
            >
              {{ menu.name }}
            </div>
          </div>
        </template>
        <div class="anchor-poiont-icon anchor-point-style">
          <svg-icon size="30" name="anchor-position" />
        </div>
      </a-popover>
    </div>
  </div>
</template>
<style lang="scss">
.common-info-header {
  display: flex;
  align-items: center;
  padding: 0 10px;
  &-name {
    min-width: 90px;
    display: inline-block;
    font-weight: bold;
    font-size: 22px;
    color: $color-text-primary;
    margin-right: 20px;
  }
  .line {
    flex: 1;
    height: 1px;
    border: 1px dashed #d3deea;
  }
  .link {
    padding: 0 10px 0 20px;
    font-weight: bold;
    font-size: 16px;
    color: #4d789c;
    display: flex;
    align-items: center;
    cursor: pointer;
    .svg-icon {
      margin-right: 6px;
    }
  }
}
.anchor-point-popover {
  .ant-popover-inner {
    padding: 0;
  }
  .anchor-point-popover-list {
    padding: 10px 0;
  }
  .anchor-point-popover-item {
    width: 140px;
    height: 46px;
    display: flex;
    align-items: center;
    cursor: pointer;
    padding-left: 20px;
    font-weight: 500;
    font-size: 16px;
    color: $color-text-regular;
    &:hover {
      background: #f9f9f9;
      font-weight: bold;
      color: $color-action;
    }
  }
  .anchor-point-enPopover-item {
    width: 270px;
  }
}
</style>
<style lang="scss" scoped>
.home-main {
  background: #f6f9fc;
  padding: 30px 20px;
  .anchor-point {
    position: fixed;
    z-index: 999;
    right: 20px;
    bottom: 100px;
    .scroll-top {
      margin-bottom: 17px;
    }
    .svg-icon {
      color: #fff;
    }
    .anchor-point-style {
      cursor: pointer;
      width: 60px;
      height: 60px;
      background: #729db0;
      box-shadow: 0px 0px 6px 1px rgba(0, 41, 75, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      &:hover {
        background: #97b7c5;
      }
    }
  }
  #policy-info-view {
    padding-top: 50px;
  }
  #claim-info-view {
    padding-top: 50px;
  }
  #auth-info-view {
    padding-top: 50px;
  }
  #ob-info-view {
    padding-top: 50px;
  }
}
</style>
